﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web.UI.WebControls;
using ServerApi.Controllers;
using ServerApi.Models;
using ServerApi.Models.Menu;
using TuyennvLibrary.Utl;

namespace ServerApi.administrator
{
    public partial class RoleUserManager : System.Web.UI.Page
    {
        public string title = "Thêm mới loại quyền cho User";
        public int stt = 1;
        public string message = "";
        RoleModel roleModel = new RoleModel();
        RoleUserModel roleUserModel = new RoleUserModel();
        AccountModel accModel = new AccountModel();
        TypeRoleModel typeModel = new TypeRoleModel();
        protected void Page_Load(object sender, EventArgs e)
        {
            AdminController.checkLogin(Session, Request, Response);
            //AdminController.checkPermission(Page, this.GetType(), Session, Request, Response);
            if (!IsPostBack)
            {
                loadTypeRole();
                loadRole();
                loadAccount();
                if (!string.IsNullOrEmpty(Request["id"]))
                {
                    int id = int.Parse(Request["id"]);
                    loadInfo(id);
                    title = "Update quyền cho User";
                }
                else
                {
                    title = "Thêm mới quyền cho User";
                }
                loadData();
            }
        }
        private void loadTypeRole()
        {
            DataTable dt = typeModel.GetListAll();
            ddlTypeRole.DataSource = dt;
            ddlTypeRole.DataTextField = "Name";
            ddlTypeRole.DataValueField = "id";
            ddlTypeRole.DataBind();

        }
        private void loadRole()
        {
            DataTable dt = roleModel.GetListBy(new string[] { Role.COLUMN_TYPEROLEID }, new object[] { ddlTypeRole.Text }, Role.COLUMN_NAME);
            ddlRole.DataSource = dt;
            ddlRole.DataTextField = "Name";
            ddlRole.DataValueField = "id";
            ddlRole.DataBind();
        }
        private void loadAccount()
        {
            DataTable dt = accModel.GetListAll();
            ddlAccount.DataSource = dt;
            ddlAccount.DataTextField = "UserName";
            ddlAccount.DataValueField = "id";
            ddlAccount.DataBind();

            ddlAccountSearch.DataSource = dt;
            ddlAccountSearch.DataTextField = "UserName";
            ddlAccountSearch.DataValueField = "id";
            ddlAccountSearch.DataBind();
        }
        private void loadInfo(int id)
        {
            RoleUser obj = roleUserModel.GetByID(id);
            loadInfo(obj);
        }

        private void loadInfo(RoleUser obj)
        {
            ddlAccount.Text = obj.UserId.ToString();
            ddlRole.Text = obj.RoleId.ToString();
            Role role = roleModel.GetByID(obj.RoleId);
            ddlTypeRole.Text = role.TypeRoleId.ToString();
        }
        private void loadData()
        {
            DataTable dt = roleUserModel.Search(txtNameSearch.Text, int.Parse(ddlAccountSearch.Text));
            GrvList.DataSource = dt;
            GrvList.DataBind();
        }
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                RoleUser obj = new RoleUser();
                obj.RoleId = int.Parse(ddlRole.Text);
                obj.UserId = int.Parse(ddlAccount.Text);
                ddlAccountSearch.Text = ddlAccount.Text;
                if (roleUserModel.GetListBy(new string[] {RoleUser.COLUMN_ROLEID,RoleUser.COLUMN_USERID }, new object[] {obj.RoleId,obj.UserId }, null).Rows.Count > 0)
                {
                    throw new Exception("User đã tồn tại quyền này");
                }
                if (!string.IsNullOrEmpty(Request["id"]))
                {
                    obj.Id = int.Parse(Request["id"]);
                    roleUserModel.Update(obj);
                    message = Utilities.getSuccessMessage("Update quyền thành công");
                }
                else
                {
                    roleUserModel.Insert(obj);
                    message = Utilities.getSuccessMessage("Thêm mới quyền thành công");
                }
                RefeshRole(obj.UserId);
                loadData();
            }
            catch (Exception ex)
            {
                message = Utilities.getErrorMessage("Lỗi: " + ex.Message);
            }
        }
        private void RefeshRole(int userid)
        {
            if (Session["userid"] != null)
            {
                int CurentUserid = int.Parse(Session["userid"].ToString());
                if (CurentUserid == userid)
                {
                    List<Role> listrole = new RoleModel().getListRoleBy(CurentUserid);
                    Session["listrole"] = listrole;
                    Session["listmenu"] = AdminController.getListMenuCatgories(CurentUserid);
                    Response.Redirect("RoleUserManager.aspx");
                }
            }
            
        }
        protected void btnSearch_Click(object sender, EventArgs e)
        {
            loadData();
        }

        protected void ddlTypeRole_SelectedIndexChanged(object sender, EventArgs e)
        {
            loadRole();
        }

        protected void GrvList_RowDeleting(object sender, System.Web.UI.WebControls.GridViewDeleteEventArgs e)
        {
            int id = int.Parse(GrvList.DataKeys[e.RowIndex].Value.ToString());
            RoleUser roleUser = roleUserModel.GetByID(id);
            if (roleUserModel.Delete(id))
            {
                RefeshRole(roleUser.UserId);
                loadData();
                Utilities.Alert(Page, this.GetType(), "Đã xóa quyền thành công");
            }
        }

        protected void GrvList_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton l = (LinkButton)e.Row.FindControl("lbtnDel");
                l.Attributes.Add("onclick", "javascript:return " +
                "confirm('Bạn có muốn xóa ứng dụng này không? " + "')");
            }
        }


    }
}